package com.aid.winter.service.impl;

import com.aid.winter.common.exception.BusinessException;
import com.aid.winter.common.constant.BatchConstants;
import com.aid.winter.dto.request.BatchCreateRequest;
import com.aid.winter.dto.request.BatchUpdateRequest;
import com.aid.winter.dto.response.BatchStatisticsVO;
import com.aid.winter.dto.response.BatchVO;
import com.aid.winter.dto.response.PageResult;
import com.aid.winter.entity.AidBatch;
import com.aid.winter.mapper.AidBatchMapper;
import com.aid.winter.service.AidBatchService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class AidBatchServiceImpl implements AidBatchService {

    private final AidBatchMapper batchMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BatchVO createBatch(BatchCreateRequest request) {
        validateTimeRange(request.getStartTime(), request.getEndTime());
        
        AidBatch batch = new AidBatch();
        BeanUtils.copyProperties(request, batch);
        
        batch.setBatchCode(generateBatchCode(request.getAcademicYear()));
        batch.setStatus(BatchConstants.STATUS_ACTIVE);
        // TODO: 设置创建人信息，需要集成认证后获取
        batch.setCreatorId(1L);
        batch.setCreatorName("admin");
        
        batchMapper.insert(batch);
        
        return convertToVO(batch);
    }

    @Override
    public PageResult<BatchVO> listBatches(String academicYear, Integer status, Integer pageNum, Integer pageSize) {
        // 计算偏移量
        int offset = (pageNum - 1) * pageSize;
        
        // 查询数据
        List<AidBatch> batchList = batchMapper.selectList(academicYear, status, offset, pageSize);
        long total = batchMapper.selectCount(academicYear, status);
        
        // 转换为VO
        List<BatchVO> voList = batchList.stream()
                .map(this::convertToVO)
                .toList();
        
        return PageResult.build(voList, total, pageSize, pageNum);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BatchVO updateBatch(Long id, BatchUpdateRequest request) {
        AidBatch batch = getBatchById(id);
        validateTimeRange(request.getStartTime(), request.getEndTime());
        validateStatus(request.getStatus());
        
        BeanUtils.copyProperties(request, batch);
        batchMapper.updateById(batch);
        
        return convertToVO(batch);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long id) {
        AidBatch batch = getBatchById(id);
        batchMapper.deleteById(id);
    }

    @Override
    public BatchVO getBatchDetail(Long id) {
        return convertToVO(getBatchById(id));
    }

    @Override
    public boolean checkBatchAvailable(Long id) {
        AidBatch batch = getBatchById(id);
        LocalDateTime now = LocalDateTime.now();
        return batch.getStatus() == BatchConstants.STATUS_ACTIVE && 
               now.isAfter(batch.getStartTime()) && 
               now.isBefore(batch.getEndTime());
    }

    @Override
    public BatchStatisticsVO getBatchStatistics() {
        String currentYear = String.valueOf(LocalDateTime.now().getYear());
        return batchMapper.selectBatchStatistics(currentYear);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateStatus(List<Long> ids, Integer status) {
        validateStatus(status);
        
        if (ids == null || ids.isEmpty()) {
            return;
        }
        
        batchMapper.updateBatchStatus(ids, status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        batchMapper.deleteBatchByIds(ids);
    }

    private AidBatch getBatchById(Long id) {
        AidBatch batch = batchMapper.selectById(id);
        if (batch == null) {
            throw new BusinessException("批次不存在");
        }
        return batch;
    }

    private void validateTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        if (endTime.isBefore(startTime)) {
            throw new BusinessException("截止时间不能早于开始时间");
        }
    }

    private String generateBatchCode(String academicYear) {
        return BatchConstants.BATCH_CODE_PREFIX + 
               academicYear.replace("-", "") + 
               UUID.randomUUID().toString()
                   .substring(0, BatchConstants.BATCH_CODE_RANDOM_LENGTH)
                   .toUpperCase();
    }

    private BatchVO convertToVO(AidBatch batch) {
        BatchVO vo = new BatchVO();
        BeanUtils.copyProperties(batch, vo);
        return vo;
    }

    private void validateStatus(Integer status) {
        if (!BatchConstants.STATUS_CLOSED.equals(status) && 
            !BatchConstants.STATUS_ACTIVE.equals(status)) {
            throw new BusinessException("无效的状态值");
        }
    }
}